package com.xhorse.lockplatform.service.impl;

import com.xhorse.lockplatform.comm.constant.FilePathDefine;
import com.xhorse.lockplatform.comm.model.BaseQuery;
import com.xhorse.lockplatform.comm.service.BaseService;
import com.xhorse.lockplatform.comm.util.DecriptUtil;
import com.xhorse.lockplatform.comm.util.Paginator;
import com.xhorse.lockplatform.comm.util.StringUtil;
import com.xhorse.lockplatform.dao.mapper.XhErrorLibMapper;
import com.xhorse.lockplatform.dao.mapper.XhFeedbackMapper;
import com.xhorse.lockplatform.model.XhErrorLib;
import com.xhorse.lockplatform.model.XhFeedbackWithBLOBs;
import com.xhorse.lockplatform.model.pojo.XhFeedBackPojo;
import com.xhorse.lockplatform.service.FeedBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FeedBackServiceImpl extends BaseService<XhFeedBackPojo> implements FeedBackService {

    @Autowired
    private XhErrorLibMapper xhErrorLibMapper;

    @Autowired
    private XhFeedbackMapper xhFeedbackMapper;

    /**
     * 获取反馈问题标签
     */
    @Override
    public List<XhErrorLib> getErrorLib(byte type, byte languageId) {
        Paginator page = new Paginator();
        FeedBackInfoQuery query = new FeedBackInfoQuery();
        query.setType(type);
        query.setLanguageId(languageId);
        page.setQuery(query);
        page.setPageless(true);
        return xhErrorLibMapper.select(page);
    }

    /**
     * 提交反馈问题
     */
    @Override
    public boolean uploadFeedBack(XhFeedbackWithBLOBs feedback) {
        StringBuilder stringBuilder = new StringBuilder();
        List<String> base64Array = new ArrayList<>();
        if (StringUtil.isNotNil(feedback.getFile1())) {
            base64Array.add(feedback.getFile1());
        }
        if (StringUtil.isNotNil(feedback.getFile2())) {
            base64Array.add(feedback.getFile2());
        }
        if (StringUtil.isNotNil(feedback.getFile3())) {
            base64Array.add(feedback.getFile3());
        }
        if (StringUtil.isNotNil(feedback.getFile4())) {
            base64Array.add(feedback.getFile4());
        }
        // 生成md5值，用于检测重复提交信息
        if (feedback.getSuccess()) {
            stringBuilder.append(feedback.getCustomerId()).append(
                    feedback.getYear());
            for (int i = 0; i < base64Array.size(); i++) {
                stringBuilder.append(base64Array.get(i));
            }
        } else {
            stringBuilder.append(feedback.getCustomerId())
                    .append(feedback.getYear()).append(feedback.getErrorCode())
                    .append(feedback.getFeedBack())
                    .append(feedback.getAdditional()).append(feedback.getVin());
        }
        feedback.setMd5(DecriptUtil.MD5(stringBuilder.toString()));
        // 将提交的数据持久化
        Paginator page = new Paginator();
        FeedBackInfoQuery query = new FeedBackInfoQuery();
        query.setMd5(feedback.getMd5());
        page.setQuery(query);
        page.setPageless(true);
        if (!xhFeedbackMapper.select(page).isEmpty()) {
            return false;
        } else {
            if (feedback.getSuccess()) { // 若通过防重校验，并且为成功反馈，则保存文件
                String picName = "";
                for (int i = 0; i < base64Array.size(); i++) {
                    // 给解码文件生成文件名
                    SimpleDateFormat sdf = new SimpleDateFormat(
                            "yy-MM-dd_HH_mm_ss");
                    String date = sdf.format(new Date());
                    // 生成文件名称并获取文件的格式
                    String filename = feedback.getCustomerId() + "_" + date
                            + "_" + i + ".png";
                    // 文件解码并保存
                    DecriptUtil.decodeBase64File(base64Array.get(i), FilePathDefine.KEY_UPLOAD_PATH + filename);
                    // 将文件名信息存入数据库
                    if (i == base64Array.size() - 1) {
                        picName += filename; // 最后一个文件不需要加逗号分隔
                    } else {
                        picName += filename + ","; // 文件名称以逗号分隔
                    }
                }
                feedback.setPictureName(picName);
            } else {
                // 根据错误码获取错误信息,并设置成错误信息便于前端显示
                String errorName = "";
                String[] errorCodeArray = feedback.getErrorCode().split(",");
                for (int i = 0; i < errorCodeArray.length; i++) {
                    errorName += (i + 1 + "." + xhErrorLibMapper
                            .selectByPrimaryKey(
                                    Integer.valueOf(errorCodeArray[i]))
                            .getDescription());
                }
                // 反馈信息插入数据库
                feedback.setErrorName(errorName);
            }
            xhFeedbackMapper.insertSelective(feedback);
            return true;
        }
    }

    /**
     * 在后台页面显示反馈信息
     */
    @Override
    public List<XhFeedBackPojo> getFeedback(Paginator page, byte success, int type) {
        List<XhFeedBackPojo> list = new ArrayList<>();
        if (type == 1) {
            list = this.listByOther(page, xhFeedbackMapper.selectRemotePagedList(page));
        } else if (type == 3) {
            list = this.listByOther(page, xhFeedbackMapper.selectChipPagedList(page));
        }
        for (XhFeedBackPojo xhFeedBackPojo : list) {
            if (success == 1) {
                String[] fielName = xhFeedBackPojo.getPictureName().split(",");
                xhFeedBackPojo.setImagesPathList(fielName);
            }
        }
        return list;
    }

    // 查询参数bean
    private static class FeedBackInfoQuery extends BaseQuery {
        private int type;
        private String md5;
        private int languageId;
        private String customerId;
        private byte success;

        public void setType(int type) {
            this.type = type;
            this.addItem("type", type);
        }

        public void setMd5(String md5) {
            this.md5 = md5;
            this.addItem("md5", md5);
        }

        public void setLanguageId(int languageId) {
            this.languageId = languageId;
            this.addItem("languageId", languageId);
        }

        public void setCustomerId(String customerId) {
            this.customerId = customerId;
            this.addItem("customerId", customerId);
        }

        public void setSuccess(byte success) {
            this.success = success;
            this.addItem("success", success);
        }
    }

}
